package com.siteseat.common.json.prettyprint;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;

import com.siteseat.common.json.JacksonMapper;

public class PrettyPrintIndenter {
  public static String indentJSON( String jsonIn ) throws IOException {
    if( ( jsonIn == null ) || ( jsonIn.length() == 0 ) ) {
      return jsonIn;
    }

    JsonFactory fac = new JsonFactory();
    JsonParser parser = fac.createJsonParser( new StringReader( jsonIn ) );
    ObjectMapper mapper = JacksonMapper.MAPPER;
    JsonNode node = null;

    node = mapper.readTree( parser );

    StringWriter out = new StringWriter();

    JsonGenerator gen = fac.createJsonGenerator( out );
    gen.useDefaultPrettyPrinter();

    mapper.writeTree( gen, node );

    gen.flush();
    gen.close();
    return out.toString();
  }
}